package com.gitee.cui.zookeeper.nameservice;

import com.gitee.cui.zk.ZKclient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

/**
 * 雪花算法id生成器
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021-11-06 12:31
 **/
public class SnowflakeIdWorker {

	private String prefixName = "/test/IDMaker/worker-";

	private String nodeName;

	private Long nodeId;

	private CuratorFramework client;

	public static final SnowflakeIdWorker INSTANCE = new SnowflakeIdWorker();

	private SnowflakeIdWorker() {
		client = ZKclient.instance.getClient();
		init();
	}

	/**
	 * 创建顺序节点
	 */
	private void init() {
		byte[] payload = prefixName.getBytes();
		try {
			nodeName = client.create()
					.creatingParentsIfNeeded()
					.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
					.forPath(prefixName, payload);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public long getNodeId() {
		if (nodeId != null) {
			return nodeId;
		}
		String sid = null;

		if (nodeName == null) {
			throw new RuntimeException("节点注册失败！");
		}

		int index = nodeName.lastIndexOf(prefixName);
		if (index >= 0) {
			index += prefixName.length();
			sid = index <= nodeName.length() ? nodeName.substring(index) : "";
		}

		if (sid == null) {
			throw new RuntimeException("节点id生成失败！");
		}

		nodeId = Long.parseLong(sid);
		return nodeId;
	}
}
